package com.sunday.fangbeibei.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.RequestParams;
import com.sunday.fangbeibei.R;
import com.sunday.fangbeibei.activity.AreaSelectActivity;
import com.sunday.fangbeibei.activity.HouseDetailActivity;
import com.sunday.fangbeibei.adapter.AdvertisementAdapter;
import com.sunday.fangbeibei.adapter.HouseAdapter;
import com.sunday.fangbeibei.cache.ApplicationCache;
import com.sunday.fangbeibei.constants.ApplicationConstants;
import com.sunday.fangbeibei.http.HttpResponseInterface;
import com.sunday.fangbeibei.http.HttpTool;
import com.sunday.fangbeibei.orm.Advertisement;
import com.sunday.fangbeibei.orm.BaseResult;
import com.sunday.fangbeibei.orm.HouseInfo;
import com.sunday.fangbeibei.orm.HouseInfoResult;

/**
 * 

* @ClassName: IndexFragment 

* @Description: TODO(楼盘fragment) 

* @author sunshineHu hucx@itouch.com.cn

* @date 2015年1月21日 上午10:00:43 

*
 */
public class HouseFragment extends Fragment implements OnClickListener,OnRefreshListener2<ListView>,OnItemClickListener,HttpResponseInterface {

	private PullToRefreshListView mPullToRefreshListView;
	private ListView listview;
	
	private ViewPager viewpager;
	private ScheduledExecutorService scheduledExecutorService;
	private int selectNow=0;
	
	private Activity parent;
	
	private HouseAdapter adapter;
	
	private int pageNo=1;
	
	private TextView area;
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		parent=getActivity();
		loadView();
		//loadAds();
		
		if(ApplicationCache.INSTANCE.getAreaInfo()!=null){
			area.setText(ApplicationCache.INSTANCE.getAreaInfo().getName()+" ");
		}else{
			area.setText("选择城市 ");
		}
		pageNo=1;
		loadData();
		
	}

	
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.house_fragment, null);
	}

	
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==111){
			if(resultCode==Activity.RESULT_OK){
				if(ApplicationCache.INSTANCE.getAreaInfo()!=null){
					area.setText(ApplicationCache.INSTANCE.getAreaInfo().getName()+" ");
				}else{
					area.setText("选择城市 ");
				}
				pageNo=1;
				loadData();
			}
		}
	}




	private void loadView(){
		
		area=(TextView) parent.findViewById(R.id.area);
		
		viewpager=new ViewPager(parent);
		viewpager.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,  (int) (parent.getWindowManager().getDefaultDisplay().getWidth()/4.383)));
		LinearLayout housell=(LinearLayout) parent.findViewById(R.id.housell);
		housell.addView(viewpager, 1);
		
		mPullToRefreshListView=(PullToRefreshListView) parent.findViewById(R.id.listview);
		listview=mPullToRefreshListView.getRefreshableView();
		mPullToRefreshListView.setOnRefreshListener(this);
		listview.setOnItemClickListener(this);

		mPullToRefreshListView.setMode(Mode.BOTH);
		mPullToRefreshListView.getLoadingLayoutProxy(false, true).setPullLabel("上拉加载");
		mPullToRefreshListView.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载");
		mPullToRefreshListView.getLoadingLayoutProxy(false, true).setReleaseLabel("松开加载更多");

		listview.setOnItemClickListener(this);
		
		area.setOnClickListener(this);
		
	}
	
	private void loadAds(List<String> lists){
		/*List<String> lists=new ArrayList<String>();
		lists.add("drawable://"+R.drawable.banner1);
		lists.add("drawable://"+R.drawable.banner2);
		lists.add("drawable://"+R.drawable.banner3);
		lists.add("drawable://"+R.drawable.banner4);*/
		AdvertisementAdapter adapter=new AdvertisementAdapter(parent, lists, this, true);
		viewpager.setAdapter(adapter);
		if(scheduledExecutorService==null){
			scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
			// 当Activity显示出来后，每3秒钟切换一次图片显示
			scheduledExecutorService.scheduleAtFixedRate(scrollImage, 3, 3, TimeUnit.SECONDS);
		}
		
	}
	

	private void loadData(){
		
		RequestParams params=new RequestParams();
		params.add("userId", ApplicationCache.INSTANCE.getUserInfo().getId());
		if(ApplicationCache.INSTANCE.getAreaInfo()!=null){
			if(ApplicationCache.INSTANCE.getAreaInfo().getId()!=null){
				params.add("filter_L_areaId", ApplicationCache.INSTANCE.getAreaInfo().getId());//areaid
			}else{
				if(ApplicationCache.INSTANCE.getAreaInfo().getParentId()!=null){
					params.add("filter_L_districtId", ApplicationCache.INSTANCE.getAreaInfo().getParentId());
				}
			}
		}
		params.add("pageIndex", pageNo+"");
		params.add("pageSize", "10");
		HttpTool.HttpPost(0, parent, ApplicationConstants.SERVER_URL+"/mobi/premises/getpilist", params, this, new TypeToken<HouseInfoResult>() {
		}.getType());
		
		RequestParams params2=new RequestParams();
		HttpTool.HttpPost(1, parent, ApplicationConstants.SERVER_URL+"/mobi/ad/list", params2, this, new TypeToken<BaseResult<List<Advertisement>>>() {
		}.getType());
	}
	
	
	
	private Runnable scrollImage=new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			if(selectNow>=4){
				selectNow=0;
			}else{
				selectNow++;
			}
			parent.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					viewpager.setCurrentItem(selectNow);// 切换当前显示的图片
				}
			});
		}
	};

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		HouseInfo info=(HouseInfo) view.getTag();
		Intent in=new Intent(getActivity(), HouseDetailActivity.class);
		in.putExtra("info", info);
		startActivity(in);
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		pageNo=1;
		loadData();
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		pageNo++;
		loadData();
	}

	@Override
	public void onResponse(int requsetCode, boolean resultStatus, Object result) {
		// TODO Auto-generated method stub
		switch(requsetCode){
		
		case 0:
			mPullToRefreshListView.onRefreshComplete();
			HouseInfoResult re=(HouseInfoResult) result;
			if(resultStatus){
				if(re.getList()!=null&&re.getList().size()>0){
					if(pageNo==1){
						adapter=new HouseAdapter(parent, re.getList());
						listview.setAdapter(adapter);
					}else{
						adapter.updateData(re.getList());
						adapter.notifyDataSetChanged();
					}
				}else{
					if(pageNo==1){
						Toast.makeText(parent, "该区域没有楼盘！", Toast.LENGTH_SHORT).show();
						adapter=new HouseAdapter(parent, new ArrayList<HouseInfo>());
						listview.setAdapter(adapter);
					}else{
						Toast.makeText(parent, "没有数据了！", Toast.LENGTH_SHORT).show();
					}
				}
			}
			break;
		case 1:
			BaseResult<List<Advertisement>> res=(BaseResult<List<Advertisement>>) result;
			List<Advertisement> ads=res.getResult();
			if(ads!=null){
				List<String> lists=new ArrayList<String>();
				for(Advertisement ad:ads){
					lists.add(ad.getExt());
					loadAds(lists);
				}
			}
			break;
		}
	}

	@Override
	public void onFailure() {
		// TODO Auto-generated method stub
		mPullToRefreshListView.onRefreshComplete();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		
		case R.id.area:
			Intent in=new Intent(parent, AreaSelectActivity.class);
			startActivityForResult(in, 111);;
			break;
		
		}
	}

	
}
